import React, { Component } from 'react';
import { InboxOutlined } from '@ant-design/icons';
import { message, Upload } from 'antd';
import axios from '../../components/service/request.js';
import ParseFile from '../../components/AnalyzeFile/index.jsx';
import FetchImages from '../../components/FetchImages/index.jsx';
import './upload.less';

const { Dragger } = Upload;

class UploadExcel extends Component {
  state = {
    file: null,
    uploadedFilePath: '',
  };

  // 处理文件上传
  handleFileUpload = async (file) => {
    const formData = new FormData();
    formData.append('file', file);

    try {
      console.log('开始上传文件');
      const response = await axios.post('/common/upload', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      });
      console.log('上传成功:', response);
      this.setState({ uploadedFilePath: response.data });
      message.success(`${file.name} 文件上传成功.`);
    } catch (error) {
      console.error('上传失败:', error);
      message.error(`${file.name} 文件上传失败.`);
    }
  };

  render() {
    const { uploadedFilePath } = this.state;

    return (
      <div className="upload-excel">
        <Dragger
          name="file"
          multiple={false}
          beforeUpload={(file) => {
            const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
            if (!isExcel) {
              message.error('只能上传Excel文件!');
              return Upload.LIST_IGNORE;
            }
            return true;
          }}
          customRequest={({ file, onSuccess, onError }) => {
            this.handleFileUpload(file).then(onSuccess).catch(onError);
          }}
        >
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
          <p className="ant-upload-hint">只支持上传一个Excel文件。</p>
        </Dragger>

        {/* 解析文件组件 */}
        <ParseFile filePath={uploadedFilePath} />

        {/* 获取图片组件 */}
        <FetchImages filePath={uploadedFilePath} />
      </div>
    );
  }
}

export default UploadExcel;
